package com.LeeCode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 反转二叉树的奇数层
 */

public class Code2415 {
    public static void main(String[] args) {

    }

    public TreeNode reverseOddLevels(TreeNode root) {
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean flag = false;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<TreeNode> nodes = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (flag) nodes.add(node);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            if (flag) {
                for (int i = 0; i < size / 2; i++) {
                    int temp = nodes.get(i).val;
                    nodes.get(i).val = nodes.get(size - 1 - i).val;
                    nodes.get(size - 1 - i).val = temp;
                }
            }
            flag = !flag;
        }
        return root;
    }
}
